<?php
namespace app\util;

//use Fukuball\Jieba\Jieba;
//use Fukuball\Jieba\JiebaAnalyse;

class Tfidf{

    public $data = [];
    public $documents = [];
    public $words = [];

    public function __construct(){
        ini_set('memory_limit', '1024M');

    }

    /**
     * @return void
     */
    public function setDocuments($data){
        $this->data = $data;
        foreach ($this->data as $value){
            $this->documents[$value['tid']] = $value;
        }
    }

    /**
     * 100%对比计算
     * @param $words
     * @return array
     */
    public function search($words){
        $words_array = explode('，',$words);
        foreach ($words_array as $word){
            foreach ($this->documents as $docId => $content) {
                $count = substr_count($content['text'], $word);
                if($count>0){
                    if(isset($this->words[$docId])){
                        $this->words[$docId]['count'] += $count;
                    }else{
                        $this->words[$docId] = [
                            'docId'=>$docId,
                            'count'=>$count,
                        ];
                    }
                }
            }
        }

        usort($this->words, function($a, $b) {
            if ($a['count'] == $b['count']) {
                // 如果count相等，可以根据docId或其他条件进行排序
                // 这里我们简单地按docId升序排序
                return $a['docId'] - $b['docId'];
            }
            return $b['count'] - $a['count']; // 根据count排序
        });

        $list = [];
        foreach ($this->words as $value){
            $list[] = $this->documents[$value['docId']];
        }
        return $list;
    }

}